package com.atguigu.gmall.service.impl;

import com.atguigu.gmall.entity.CartInfo;
import com.atguigu.gmall.mapper.CartInfoMapper;
import com.atguigu.gmall.service.AsyncCartInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import sun.awt.SunHints;

import javax.xml.bind.ValidationEvent;

@Async
@Service
public class AsyncCartInfoServiceImpl extends ServiceImpl<CartInfoMapper,CartInfo> implements AsyncCartInfoService {

    @Override
    public void updateCartInfo(CartInfo cartInfoExist) {
        if (!ObjectUtils.isEmpty(cartInfoExist)) //二次检查
            baseMapper.updateById(cartInfoExist);
    }

    @Override
    public void saveCartInfo(CartInfo cartInfo) {
        if (!ObjectUtils.isEmpty(cartInfo)) //二次检查
            baseMapper.insert(cartInfo);
    }

    @Override
    public void deleteCartInfo(String userId, Long skuId) {
        QueryWrapper<CartInfo> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(userId)){
            queryWrapper.eq("user_id",userId);
        }
        if(skuId!=null){
            queryWrapper.eq("sku_id",skuId);
        }
        baseMapper.delete(queryWrapper);
    }

    @Override
    public void checkCart(String userId, Integer isChecked, Long skuId) {
        //先查询出相应的购物车信息
        QueryWrapper<CartInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("sku_id", skuId);
        CartInfo cartInfo = baseMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(cartInfo))
            return;//没有购物车信息，直接返回
        cartInfo.setIsChecked(isChecked);//有就更新状态
        baseMapper.updateById(cartInfo);
    }
}
